package cc.lucien.controller;

import cc.lucien.entity.Goods;
import cc.lucien.entity.GoodsVO;
import cc.lucien.service.GoodTypeService;
import cc.lucien.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodTypeService goodTypeService;

    /**
     * 返回 json 数据用于展示
     * @return
     */
    @GetMapping("/show")
    @ResponseBody
    public GoodsVO show() {
        GoodsVO goodsVO = new GoodsVO();
        goodsVO.setCode(0);
        goodsVO.setMsg("");
        goodsVO.setCount(200L);
        goodsVO.setData(goodsService.findAll());
        return goodsVO;
    }

    @PostMapping("/save")
    public String save(Goods goods) {
        goodsService.save(goods);
        return "goodsTable";
    }

    @GetMapping("/toUpdate/{id}")
    public ModelAndView toUpdate(@PathVariable("id") Integer id) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("goodsUpdate");
        modelAndView.addObject("goods", goodsService.findById(id));
        modelAndView.addObject("goodTypeList", goodTypeService.findAll());
        return modelAndView;
    }

    @PostMapping("/update")
    public String update(Goods goods) {
        goodsService.update(goods);
        return "goodsTable";
    }

    @GetMapping("/deleteById/{id}")
    public String deleteById(@PathVariable("id") Integer id) {
        goodsService.deleteById(id);
        return "goodsTable";
    }
}
